An assignment statement asks for the computer to perform two steps, in order:
=
=
Here is the assignment statement we are considering:
str = new String( "Elementary, my dear Watson!" );
In our program, the two steps work like this:
Evaluate the expression.
The expression
new String( "Elementary, my dear Watson!" )is evaluated. In this statement, this means that a new object is created. A reference to the object describes the object's location in memory. It enables the Java virtual computer to find the object. (A reference is like your cell phone number. Someone who has your number can contact you, no matter where you are.)
Store the value in the variable.
In the second step, the reference is stored in the reference variable:
str = The reference to the string just createdNow whenever the program needs to refer to the object it uses the variable
str
.
Sometimes the variable str
is called the "name" of the object.
This is somewhat sloppy (for reasons that are discussed in a future chapter),
but OK as long as you are careful.
Are the object and the reference variable different things?